package com.zy.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.business.domain.TbHkReady;
import com.zy.business.domain.TbRemindUser;
import com.zy.business.domain.TbVisitorInfo;
import com.zy.business.domain.TbVisitorRecord;
import com.zy.business.domain.vo.VisitorDto;
import com.zy.business.mapper.RemindUserMapper;
import com.zy.business.mapper.VisitorInfoMapper;
import com.zy.business.mapper.VisitorRecordMapper;
import com.zy.business.service.HkReadyService;
import com.zy.business.service.VisitorRecordService;
import com.zy.common.core.domain.AjaxResult;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.utils.StringUtils;
import com.zy.common.utils.WebUtil;
import com.zy.system.mapper.SysDictDataMapper;
import com.zy.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 访客记录 服务层实现
 * @author: whf
 * @create: 2022-08-01 10:12
 **/
@Service
public class VisitorRecordServiceImpl extends ServiceImpl<VisitorRecordMapper, TbVisitorRecord> implements VisitorRecordService {

    @Resource
    private VisitorInfoMapper visitorInfoMapper;

    @Resource
    private RemindUserMapper remindUserMapper;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysDictDataMapper dictMapper;

    @Value("${SUCCESS-TEMPLATEID}")
    private String successTemplateId;

    @Value("${REFUSE-TEMPLATEID}")
    private String refuseTemplateId;

    @Value("${APPID}")
    private String APPID;

    @Value("${APPSECRET}")
    private String APPSECRET;

    @Autowired
    private HkReadyService hkReadyService;

    @Override
    public List<TbVisitorRecord> queryList(VisitorDto dto) {
        List<TbVisitorRecord> recordList = baseMapper.queryList(dto);
        return recordList;
    }

    /*@Override
    @Transactional
    public AjaxResult audit(TbVisitorRecord visitorRecord, HttpServletRequest request) {
        TbVisitorRecord record = baseMapper.selectById(visitorRecord.getRecordId());
        TbVisitorInfo visitorInfo = visitorInfoMapper.selectById(record.getVisitorId());
        if (visitorRecord.getState()==1){
            TbHkReady hkReady = new TbHkReady();
            hkReady.setUserName(visitorInfo.getVisitorName());
            if(StringUtils.isNotEmpty(visitorInfo.getPhoto())){
                String address = request.getScheme() + "://" + request.getServerName();
                hkReady.setPicUrl(address+visitorInfo.getPhoto());
            }
            hkReady.setDingUserId(String.valueOf(visitorInfo.getVisitorId()));
            hkReady.setVisitorTime(record.getVisitTime());
            if (visitorInfo.getVisitNum()==0){
                hkReady.setType("addVisitor");
            }else{
                hkReady.setType("updateVisitor");
            }
            hkReadyService.add(hkReady);
            visitorInfo.setVisitNum(visitorInfo.getVisitNum()+1);
            visitorInfo.setUpdateTime(new Date());
            visitorInfoMapper.updateById(visitorInfo);
        }
        record.setState(visitorRecord.getState());
        if (StringUtils.isNotEmpty(visitorRecord.getRejectionReason())) {
            record.setRejectionReason(visitorRecord.getRejectionReason());
        }
        record.setUpdateTime(new Date());
        SysUser user = userMapper.selectUserById(record.getVisitUserId());
        record.setVisitUserName(user.getUserName());
        baseMapper.updateById(record);
        sendMessage(record);
        return AjaxResult.success();
    }*/

    @Override
    public void sendMessage(TbVisitorRecord record){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        /*TbVisitorInfo visitorInfo = visitorInfoMapper.selectById(record.getVisitorId());*/
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        JSONObject result = WebUtil.doGet(accessUrl);
        String accessToken = null;
        if (null != result) {
            accessToken = result.getString("access_token");
        }
        String templtUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
        String templateId = "";
        String firstStr = "";
        String remarkStr = "";
        String color = "#173177";
        templateId = successTemplateId;
        firstStr = "您好，您已预约成功。";
        remarkStr = "请在预约时间内到访";
        /*if (record.getState()==1){
            templateId = successTemplateId;
            firstStr = "您好，您的预约已成功。";
            remarkStr = "请在预约时间内到访，过期无效，感谢您的使用。";
        }else{
            templateId = refuseTemplateId;
            firstStr = "您好，您的预约被拒绝";
            remarkStr = "请与被访者确认后再次提交预约申请，感谢您的使用。";
            color = "#ff0000";
        }*/
        /**
         * {{first.DATA}}
         * 访客姓名：{{keyword1.DATA}}
         * 拜访对象：{{keyword2.DATA}}
         * 到访时间：{{keyword3.DATA}}
         * {{remark.DATA}}
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", record.getOpenId());   // openid
        jsonObject.put("template_id", templateId);
        //jsonObject.put("url", "http://kq.heshenghua.net/visitor/#/detail?recordId="+record.getRecordId());

        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value", firstStr);
        first.put("color", "#173177");
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", record.getVisitorName());
        keyword1.put("color", "#173177");
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", "和盛华科技");
        keyword2.put("color", "#173177");
        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", sdf.format(record.getVisitTime()));
        keyword3.put("color", "#173177");
        /*JSONObject keyword4 = new JSONObject();
        keyword4.put("value", record.getRejectionReason());
        keyword4.put("color", color);*/
        JSONObject remark = new JSONObject();
        remark.put("value", remarkStr);
        remark.put("color", "#173177");

        data.put("first",first);
        data.put("keyword1",keyword1);
        data.put("keyword2",keyword2);
        data.put("keyword3",keyword3);
        /*if (record.getState()==2){
            data.put("keyword4",keyword4);
        }*/
        data.put("remark",remark);

        jsonObject.put("data", data);

        String string = null;
        try {
            string = WebUtil.sendPostJsonStr(templtUrl, jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject result1 = JSONObject.parseObject(string);
        int errcode = result1.getIntValue("errcode");
        if(errcode == 0){
            // 发送成功
            System.out.println("发送成功");
        } else {
            // 发送失败
            System.out.println("发送失败");
        }
    }

    @Override
    public AjaxResult getRemindUser() {
        List<Map<String, Object>> maps = remindUserMapper.selectMaps(new QueryWrapper<TbRemindUser>().select("GROUP_CONCAT(user_id) AS userIds"));
        if (maps!=null && maps.size()>0){
            String userIds = (String) maps.get(0).get("userIds");
            return AjaxResult.success().put("userIds",userIds);
        }
        return AjaxResult.success().put("userIds",null);
    }

    @Override
    public TbVisitorRecord getInfo(Long recordId) {
        TbVisitorRecord record = baseMapper.selectOne(new QueryWrapper<TbVisitorRecord>().eq("record_id",recordId));
        /*TbVisitorInfo visitor = visitorInfoMapper.selectById(record.getVisitorId());
        SysUser user = userMapper.selectUserById(record.getVisitUserId());
        record.setVisitorName(visitor.getVisitorName());
        record.setPhone(visitor.getPhone());
        record.setPhoto(visitor.getPhoto());
        record.setCompanyName(visitor.getCompanyName());
        //record.setVisitUserName(user.getUserName());
        record.setIdCard(visitor.getIdCard());
        record.setVisitReasonName(dictMapper.selectDictLabel("VISIT_REASON",record.getVisitReason()));*/
        return record;
    }

    @Override
    @Transactional
    public void configUser(String userIds) {
        remindUserMapper.deleteAll();
        if (StringUtils.isNotEmpty(userIds)){
            String[] userIdArr = userIds.split(",");
            for (String userId : userIdArr) {
                TbRemindUser remindUser = new TbRemindUser();
                remindUser.setId(1L);
                remindUser.setUserId(Long.parseLong(userId));
                remindUserMapper.insert(remindUser);
            }
        }
    }
}
